<template>
  <div>
    <el-table border :data="thisValue" stripe style="width: 100%" size="mini">
       <el-table-column type="index" label="序号" width="60"> </el-table-column>
      <el-table-column
        :prop="item.field"
        :label="item.label"
        :width="item.width || 180"
        v-for="item in control.options"
        :key="item.field"
      >
        <template slot-scope="scope">
          <span v-if="!isEdit">{{ scope.row[item.field] }}</span>
          <formItem
            v-else
            :control="item"
            v-model="scope.row[item.field]"
            :isEdit="isEdit"
          ></formItem>
        </template>
      </el-table-column>
      <el-table-column > </el-table-column>
      <el-table-column fixed="right" label="操作" width="50" v-if="isEdit">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="removeItem(scope.$index)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-button type="text" size="small" @click="addItem" v-if="isEdit"
      >添加</el-button
    >
  </div>
</template>

<script>
import formItem from "./formItem";
export default {
  components: { formItem },
  props: {
    control: {
      type: Object,
      default() {
        return {
          span: 12,
          type: "table",
          field: "field",
          label: "label",
          default: "",
          options: [
            {
              type: "string",
              field: "field",
              label: "label",
              width: "180",
              default: "",
            },
          ],
        };
      },
    },
    value: null,
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  model: {
    event: "change",
    prop: "value",
  },
  data() {
    return {
      thisValue: [],
    };
  },
  watch: {
    value() {
      if (this.value instanceof Array) this.thisValue = this.value;
    },
    thisValue() {
      this.$emit("change", this.thisValue);
    },
  },
  methods: {
    addItem() {
      var item = {};
      this.control.options.forEach((op) => {
        item[op.field] = op.default;
      });
      this.thisValue.push(item);
    },
    removeItem(index) {
      this.thisValue.splice(index, 1);
    },
  },
};
</script>

<style>
</style>